const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");

const app = express();
const httpServer = createServer(app);

const io = new Server(httpServer, {
  cors: {
    origin: '*'
  }
});

// 每个房间保存最近 100 条消息
const roomMessages = {};


io.on('connection', (socket) => {
  console.log('a user connected', socket.id);

  socket.on('disconnect', () => {
    console.log('user disconnected', socket.id);
  });

  // 用户加入房间
  socket.on('join room', (userInfo, roomInfo, callback) => {


    const roomid = roomInfo.id;
    // 初始化房间消息数组
    if (!roomMessages[roomid]) roomMessages[roomid] = [];

    socket.join(roomInfo.id);

    // 通知房间内其他人
    io.to(roomInfo.id).emit("systemMessage", {
      createTime: roomInfo.timestamp,
      message: `${userInfo.name} 进入了房间${roomInfo.id}`
    });

    // ack 确认给自己
    callback?.({ success: true, room: roomInfo, message: roomMessages[roomid] });
  });

  // 用户发送信息后，进行房间广播
  socket.on('room message', (msgInfo, roomId) => {
    console.log('message from: ', msgInfo, ' in room: ', roomId);

    // 保存消息
    roomMessages[roomId].push(msgInfo);

    // 限制数组长度，保持最近 100 条
    if (roomMessages[roomId].length > 100) {
      roomMessages[roomId].shift();
    }

    socket.to(roomId).emit('room message', msgInfo);
  });

});


httpServer.listen(3000, () => {
  console.log('listening on *:3000');
});
